<?php
/**
 * Created by PhpStorm.
 * User: ytlmi
 * Date: 2018/3/7
 * Time: 11:15
 */

namespace org\util\wordTool\example;

use org\util\wordTool\Table;
use org\util\wordTool\Word;
use org\util\forensicTool\LittleTools;

class WriteReport
{
    protected $caseData = [];//案件信息
    protected $genoType = [];//样品分型数据
    protected $kit = [];//试剂盒信息，包含全名、厂家
    protected $frequency = [];//基因频率库
    protected $mutation = [];//突变率
    protected $config = [];//配置数据
    protected $word;
    protected $body;
    protected $header;
    protected $footer;
    protected static $instance;//object 对象实例

    const BODY_FONT = ['name' => '仿宋', 'size' => '四号'];
    const TABLE_DES_FONT = ['name' => '仿宋', 'size' => '五号'];
    const TABLE_FONT = ['name_zh' => '仿宋', 'name_en' => 'Times New Roman', 'size' => '五号'];
    const HEAD_FONT_1 = ['name' => '黑体', 'size' => '小二'];
    const HEAD_FONT_2 = ['name' => '黑体', 'size' => '三号'];
    const HEAD_FONT_3 = ['name' => '黑体', 'size' => '四号'];
    const TEXT_CENTER = ['align' => 'center'];
    const TEXT_RIGHT = ['align' => 'right'];
    const TEXT_LEFT = ['align' => 'left'];
    const TEXT_TAB = ['chars' => 200];
    const TABLE_STYLE = ['border' => ['top' => 'type=single,size=12', 'bottom' => 'type=single,size=12'], 'margin' => ['top' => 10, 'bottom' => 10]];
    const FIRST_ROW_STYLE = ['align' => 'center', 'vAlign' => 'center', 'border' => ['bottom' => 'type=single,size=4']];
    const MID_ROW_STYLE = ['align' => 'center', 'vAlign' => 'center', 'border' => ['top' => 'type=nil', 'bottom' => 'type=nil']];
    const LAST_ROW_STYLE = ['align' => 'center', 'vAlign' => 'center', 'border' => []];


    public function __construct()
    {
        $this->word = Word::instance();
        $this->body = $this->word->createBody(self::BODY_FONT, ['space' => 30]);
        $this->header = $this->word->createHeader(self::TABLE_FONT);
        $this->footer = $this->word->createFooter(self::TABLE_FONT);
    }

    /**
     * @return WriteReport
     * 单例模式实例化当前类
     */
    static public function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * @param array $caseData
     * @return WriteReport
     * @throws \Exception
     */
    public function setCaseData(array $caseData)
    {
        $dataMap = ['case_id', 'case_type', 'client_type', 'client_name', 'case_info', 'request_date', 'accept_date', 'end_date', 'id_kit', 'id_appraiser_0', 'id_appraiser_1', 'samples'];
        foreach ($dataMap as $item) {//验证数据完整性
            if (!isset($caseData[$item])) throw new \Exception('案件信息缺少:' . $item);
        }
        $this->caseData = $caseData;
        return $this;
    }

    /**
     * @param array $genoType
     * @return WriteReport
     */
    public function setGenoType(array $genoType)
    {
        $this->genoType = $genoType;
        return $this;
    }

    public function setKit(array $kit)
    {
        $this->kit = $kit;
        return $this;
    }

    /**
     * @param array $frequency
     * @return WriteReport
     */
    public function setFrequency(array $frequency)
    {
        $this->frequency = $frequency;
        return $this;
    }

    /**
     * @param array $mutation
     * @return WriteReport
     */
    public function setMutation(array $mutation)
    {
        $this->mutation = $mutation;
        return $this;
    }

    /**
     * @param array $config
     * @return WriteReport
     * 报告使用的配置，包含：机构名称(instFullName),机构简称(instShortName),
     */
    public function setConfig(array $config)
    {
        $this->config = $config;
        return $this;
    }

    /**
     * @throws \Exception
     */
    public function write()
    {
        $clientTypeMap = ['委 托 人', '委托单位'];
        $clientType = $clientTypeMap[$this->caseData['client_type']];
        $clientName = $this->caseData['client_name'];
        $caseMatter = $this->makeCaseMatter();
        $requestDate = LittleTools::instance()->dateToZh($this->caseData['request_date']);
        $acceptDate = LittleTools::instance()->dateToZh($this->caseData['accept_date']);
        $endDate = LittleTools::instance()->dateToZh($this->caseData['end_date']);
        $sampleTypes = $this->makeSampleTypes();
        $detect_describe = '按照' . $this->config['standard_lab'] . '附录A中的磁珠法抽提DNA，采用' . $this->kit['kit_describe'] . '（' . $this->kit['kit_company'] . '）进行复合PCR扩增，用' . $this->config['equipment_name'] . '（' . $this->config['equipment_company'] . '）进行毛细管电泳，使用' . $this->config['analyze_software'] . '进行基因型分析。';

        $this->body
            ->addPr($this->config['inst_name'], self::HEAD_FONT_1, self::TEXT_CENTER)
            ->addPr('法医物证司法鉴定意见书', self::HEAD_FONT_1, self::TEXT_CENTER)
            ->addPr($this->config['inst_brif'] . '[2017]DNA检字第107号', null, self::TEXT_RIGHT)
            ->addPr('一、基本情况', self::HEAD_FONT_2, ['spaceBefore' => 40])
            ->addBreak()
            ->addText($clientType . '：', self::HEAD_FONT_3, self::TEXT_TAB)
            ->addText($clientName, self::BODY_FONT)
            ->addBreak()
            ->addText('委托事项：', self::HEAD_FONT_3, self::TEXT_TAB)
            ->addText($caseMatter, self::BODY_FONT)
            ->addBreak()
            ->addText('委托日期：', self::HEAD_FONT_3, self::TEXT_TAB)
            ->addText($requestDate, self::BODY_FONT)
            ->addBreak()
            ->addText('受理日期：', self::HEAD_FONT_3, self::TEXT_TAB)
            ->addText($acceptDate, self::BODY_FONT)
            ->addBreak()
            ->addText('鉴定材料：', self::HEAD_FONT_3, self::TEXT_TAB)
            ->addText($sampleTypes, self::BODY_FONT)
            ->addPr('二、被鉴定人概况', self::HEAD_FONT_2, ['spaceBefore' => 40]);
        $this->addSampleTable();
        $this->body
            ->addPr('三、基本案情', self::HEAD_FONT_2, ['spaceBefore' => 40])
            ->addPr($this->caseData['case_info'], self::BODY_FONT, self::TEXT_TAB)
            ->addPr('四、检验过程', self::HEAD_FONT_2, ['spaceBefore' => 40])
            ->addPr('1、检材处理和检验方法', self::HEAD_FONT_3, self::TEXT_TAB)
            ->addPr($detect_describe, self::BODY_FONT, self::TEXT_TAB)
            ->addPr('2、检验结果', self::HEAD_FONT_3, self::TEXT_TAB)
            ->addPr('上述检材STR基因座的基因分型结果如下：', self::BODY_FONT, self::TEXT_TAB);
        $this->addDetectionTable();
        $this->word->saveDocx();
    }


    /**
     * @return array
     * 将样品按角色分组,亲子鉴定分为亲代子代两组,个体识别分为已知样和未知样两组
     */
    protected function makeRoleGroup()
    {
        $roleGroup = [[], []];
        foreach ($this->caseData['samples'] as $role => $sample) {
            if (preg_match('/(F|M|yz)/', $role)) $roleGroup[0][] = $role;
            if (preg_match('/(C|wz)/', $role)) $roleGroup[1][] = $role;
        }
        return $roleGroup;
    }

    /**
     * @return string
     * 根据样品分组生成鉴定事项文本
     */
    protected function makeCaseMatter()
    {
        $roleGroup = $this->makeRoleGroup();
        $nameStr0 = '';
        $nameStr1 = '';
        if ($this->caseData['case_type'] == 'ty') {
            $caseMatter = '同一性认定';
        } else {
            foreach ($roleGroup[1] as $role) {//用顿号连接孩子姓名
                $nameStr1 .= $this->caseData['samples'][$role]['person_name'] . '、';
            }
            if ($this->caseData['case_type'] == '3l') {
                $nameStr0 = $this->caseData['samples']['F']['person_name'] . '、';
            } else {
                foreach ($roleGroup[0] as $role) {//用顿号连接父母姓名
                    $nameStr0 .= $this->caseData['samples'][$role]['person_name'] . '、';
                }
            }
            $nameStr0 = mb_substr($nameStr0, 0, -1);
            $nameStr1 = mb_substr($nameStr1, 0, -1);
            $caseMatter = '检验' . $nameStr0 . '与' . $nameStr1 . '之间是否存在亲生血缘关系';
        }
        return $caseMatter;
    }

    /**
     * @return string
     * 生成鉴定材料描述文本
     */
    protected function makeSampleTypes()
    {
        $sampleTypes = '';
        foreach ($this->caseData['samples'] as $sample) {
            $sampleTypes .= $this->caseData['case_type'] == 'ty' ? $sample['sample_type'] . '、' : $sample['person_name'] . $sample['sample_type'] . '、';
        }
        return mb_substr($sampleTypes, 0, -1);
    }

    protected function addSampleTable()
    {
    }

    protected function addRow(Table $table, $role, $position = 'mid')
    {
    }

    protected function addDetectionTable()
    {
    }

}